package com.fuxin.controller;


import com.fuxin.client.UserClient;
import com.fuxin.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;



@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "defaultFallBack")
public class consumerController {
    /*@Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    private AtomicInteger count;*/

    @Autowired
    private UserClient userClient;

 /*   @Autowired
    private RestTemplate restTemplate;*/


    @GetMapping("{id}")
    public User queryById(@PathVariable("id") long id){
        return userClient.queryById(id);
    }


   /* @GetMapping("{id}")
    @HystrixCommand
    public String queryById(@PathVariable("id") Long id){
        String url = "http://user-service/user/" + id;
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }

    public String defaultFallBack(){
        return "默认提示：对不起，网络太拥挤了！";
    }*/



    /*@GetMapping("{id}")
    @HystrixCommand
    public String queryById(@PathVariable("id") Long id){


        *//*if(id == 1){
            throw new RuntimeException("太忙了");
        }*//*
        String url = String.format("http://user-service/user/%d",id);
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }*/

    public String defaultFallBack(){
        return "aaaaaaaaaaaaaaaaaaaaaaaaaaa,你的服务器挂了，别再请求了！！！";
    }














    /*@GetMapping("{id}")
    public User queryById(@PathVariable("id")Long id){
        根据服务ID（Spring。application。name）,获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
        轮询负载均衡
//        int index = count.getAndAdd(1) % instances.size();
//        ServiceInstance serviceInstance1 = instances.get(count++);

        取出一个服务实例
        ServiceInstance serviceInstance = instances.get(0);
        int port = serviceInstance.getPort();
        从服务中获取ip和端口
        String url = String.format("http://%s:%d/user/%s",serviceInstance.getHost(),port
               ,id);
        System.out.println("id = " + id);
//        String url = "http://localhost:8081/user/"+id;
        查询
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/













    /*@Autowired
    private RestTemplate restTemplate;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        String url = "http://localhost:8081/user/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/
}
